import { _decorator, Component, EditBox, Node } from 'cc';
import Crypt from 'jsencrypt';
import { PublicKey, RpcFunc } from '../common';
import NetworkManager from '../global/NetworkManager';

const { ccclass, property } = _decorator;

const crypt = new Crypt();
crypt.setKey(PublicKey);

@ccclass('LoginManager')
export class LoginManager extends Component {
    account: EditBox;
    password: EditBox;
    onLoad() {
        this.account = this.node.getChildByName("Account").getComponent(EditBox);
        this.password = this.node.getChildByName("Password").getComponent(EditBox);

    }

    async register() {
        console.log(this.account.string, this.password.string);
        const account = crypt.encrypt(this.account.string);
        const password = crypt.encrypt(this.password.string);
        console.log(account, password);

        const res = await fetch("http://localhost:3000/register", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ account, password }),
        }).then((response) => response.json())

        console.log('res', res);
    }


    /**
     * 登录函数
     *
     * 异步执行登录操作，加密账号和密码后发送到服务器进行验证。
     *
     * @returns 返回一个Promise，包含登录结果
     */
    async login() {

        console.log(this.account.string, this.password.string);
        // 加密账号
        const account = crypt.encrypt(this.account.string);
        // 加密密码
        const password = crypt.encrypt(this.password.string);
        // 打印加密后的账号和密码
        console.log(account, password);

        // 发起POST请求到登录接口
        const res = await fetch("http://localhost:3000/login", {
            method: "POST",
            headers: {
                // 设置请求头为JSON类型
                "Content-Type": "application/json",
            },
            // 请求体为JSON字符串
            body: JSON.stringify({ account, password }),
        }).then((response) => response.json())

        // 打印响应结果
        console.log('res', res);

        this.connect(res.token);
    }


    async connect(token: string) {
        await NetworkManager.Instance.connect();
        const res = await NetworkManager.Instance.call(RpcFunc.enterGame, {
            token,
        });

        console.log('connect', res);
    };
}


